<script setup lang="ts">
import { ref, computed } from 'vue'
import BusinessModel from '@/models/BusinessModel'
import { showConfirm } from '@/utils'
import useApi from '@/core/apiStore'
import { chain } from 'lodash'

const apiStore = useApi()

const props = defineProps({
  saveCallback: {
    type: Function,
    required: true,
    validator: (value: Function) => typeof value === 'function',
  },
})

const visible = ref(false)
const isEditing = ref(false)
const formData = ref<BusinessModel>(BusinessModel.createDefault())
const newSection = ref('')
const computedClusters = computed(() => {
  return chain(apiStore.apiStates.getClusters.data.data.clusters)
    .map(item => ({ label: item.name, value: item.name }))
    .value()
})

const show = (business?: BusinessModel) => {
  isEditing.value = business !== undefined
  if (business) {
    formData.value = { ...business }
  } else {
    formData.value = BusinessModel.createDefault()
  }
  visible.value = true
}

const handleSave = async () => {
  const shouldClose = await props.saveCallback(formData.value)
  if (shouldClose) {
    visible.value = false
  }
}

const handleCancel = () => {
  visible.value = false
}

const addSection = () => {
  if (newSection.value.trim()) {
    if (!formData.value.sections) {
      formData.value.sections = []
    }
    formData.value.sections.push(newSection.value)
    newSection.value = ''
  }
}

const removeSection = (index: number) => {
  showConfirm('确定要删除该业务板块吗?', () => {
    if (formData.value.sections) {
      formData.value.sections.splice(index, 1)
    }
  })
}

const handleDragStart = (e: DragEvent, index: number) => {
  e.dataTransfer?.setData('text/plain', index.toString())
}

const handleDragOver = (e: DragEvent) => {
  e.preventDefault()
}

const handleDrop = (e: DragEvent, targetIndex: number) => {
  e.preventDefault()
  if (!formData.value.sections) return

  const draggedIndex = Number(e.dataTransfer?.getData('text/plain'))
  if (isNaN(draggedIndex) || draggedIndex === targetIndex) return

  const sections = [...formData.value.sections]
  const [removed] = sections.splice(draggedIndex, 1)
  sections.splice(targetIndex, 0, removed)
  formData.value.sections = sections
}

defineExpose({
  show,
})
</script>

<template>
  <el-dialog
    v-model="visible"
    :title="isEditing ? '编辑业务' : '新增业务'"
    width="50%"
  >
    <el-form :model="formData" label-width="120px">
      <el-form-item label="业务名称">
        <el-input v-model="formData.name" />
      </el-form-item>
      <el-form-item label="集群">
        <el-select
          v-model="formData.clusters"
          multiple
          filterable
          allow-create
          default-first-option
          placeholder="集群，可多选"
          style="width: 100%"
        >
          <el-option
            v-for="item in computedClusters"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="业务Topo分区">
        <div class="section-list">
          <div
            v-for="(section, index) in formData.sections"
            :key="index"
            class="section-item"
            draggable="true"
            @dragstart="handleDragStart($event, index)"
            @dragover="handleDragOver($event)"
            @drop="handleDrop($event, index)"
          >
            <span>{{ section }}</span>
            <el-button type="danger" size="small" @click="removeSection(index)">
              删除
            </el-button>
          </div>
          <div class="section-add">
            <el-input v-model="newSection" placeholder="输入新业务板块" />
            <el-button type="primary" @click="addSection">添加</el-button>
          </div>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.section-list {
  width: 100%;
}
.section-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  padding: 8px;
  border: 1px solid #eee;
  border-radius: 4px;
  cursor: move;
  background-color: white;
  transition: all 0.2s;
}
.section-item:hover {
  background-color: #f5f7fa;
}
.section-add {
  display: flex;
  gap: 8px;
  margin-top: 16px;
}
</style>
